'use client'

import { useState } from 'react'
import { Layout, Menu, Input, Avatar, Button, Card, Typography, Space, Divider, Dropdown, Modal, Form, message } from 'antd'
import {
  HomeOutlined,
  FileTextOutlined,
  CodeOutlined,
  SettingOutlined,
  SearchOutlined,
  UserOutlined,
  MessageOutlined,
  ToolOutlined,
  BookOutlined,
  CalculatorOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LoginOutlined,
  LogoutOutlined,
  UserAddOutlined,
  SettingOutlined as SettingIcon
} from '@ant-design/icons'

const { Header, Sider, Content } = Layout
const { Title, Text } = Typography

// 功能菜单配置
const menuItems = [
  {
    key: 'home',
    icon: <HomeOutlined />,
    label: '首页',
  },
  {
    key: 'writing',
    icon: <FileTextOutlined />,
    label: '写作助手',
  },
  {
    key: 'code',
    icon: <CodeOutlined />,
    label: '代码生成',
  },
  {
    key: 'chat',
    icon: <MessageOutlined />,
    label: 'AI 对话',
  },
  {
    key: 'tools',
    icon: <ToolOutlined />,
    label: '实用工具',
    children: [
      {
        key: 'calculator',
        icon: <CalculatorOutlined />,
        label: '计算器',
      },
      {
        key: 'converter',
        icon: <ToolOutlined />,
        label: '格式转换',
      },
    ],
  },
  {
    key: 'docs',
    icon: <BookOutlined />,
    label: '文档中心',
  },
  {
    key: 'settings',
    icon: <SettingOutlined />,
    label: '设置',
  },
]

export default function Page() {
  const [selectedKey, setSelectedKey] = useState('home')
  const [collapsed, setCollapsed] = useState(false)
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [userInfo, setUserInfo] = useState({ name: '用户', email: 'user@example.com' })
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [modalType, setModalType] = useState<'login' | 'register'>('login')
  const [form] = Form.useForm()

  // 用户下拉菜单配置
  const userMenuItems = isLoggedIn ? [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    {
      key: 'settings',
      icon: <SettingIcon />,
      label: '账户设置',
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ] : [
    {
      key: 'login',
      icon: <LoginOutlined />,
      label: '登录',
    },
    {
      key: 'register',
      icon: <UserAddOutlined />,
      label: '注册',
    },
  ]

  // 处理用户菜单点击
  const handleUserMenuClick = ({ key }: { key: string }) => {
    switch (key) {
      case 'login':
        setModalType('login')
        setIsModalVisible(true)
        form.resetFields()
        break
      case 'register':
        setModalType('register')
        setIsModalVisible(true)
        form.resetFields()
        break
      case 'logout':
        setIsLoggedIn(false)
        setUserInfo({ name: '用户', email: 'user@example.com' })
        message.success('已退出登录')
        break
      case 'profile':
        // 处理个人资料逻辑
        console.log('用户点击个人资料')
        break
      case 'settings':
        // 处理设置逻辑
        console.log('用户点击账户设置')
        break
    }
  }

  // 处理登录/注册表单提交
  const handleFormSubmit = async (values: any) => {
    try {
      if (modalType === 'login') {
        // 模拟登录逻辑
        console.log('登录信息:', values)
        setIsLoggedIn(true)
        setUserInfo({ name: values.username || '用户', email: values.email || 'user@example.com' })
        message.success('登录成功！')
        setIsModalVisible(false)
      } else {
        // 模拟注册逻辑
        console.log('注册信息:', values)
        message.success('注册成功！请登录')
        setModalType('login')
        form.setFieldsValue({ username: values.username, email: values.email })
      }
    } catch (error) {
      message.error('操作失败，请重试')
    }
  }

  // 处理模态框取消
  const handleModalCancel = () => {
    setIsModalVisible(false)
    form.resetFields()
  }

  // 切换登录/注册模式
  const switchModalType = () => {
    setModalType(modalType === 'login' ? 'register' : 'login')
    form.resetFields()
  }

  // 渲染不同的功能组件
  const renderContent = () => {
    switch (selectedKey) {
      case 'home':
        return <HomeContent />
      case 'writing':
        return <WritingContent />
      case 'code':
        return <CodeContent />
      case 'chat':
        return <ChatContent />
      case 'calculator':
        return <CalculatorContent />
      case 'converter':
        return <ConverterContent />
      case 'docs':
        return <DocsContent />
      case 'settings':
        return <SettingsContent />
      default:
        return <HomeContent />
    }
  }

  return (
    <Layout className="layout-container">
      {/* 左侧菜单 */}
      <Sider 
        width={240} 
        collapsed={collapsed}
        className="sidebar"
        theme="light"
        trigger={null}
      >
        <div style={{ padding: '16px', textAlign: 'center' }}>
          <Title level={4} style={{ margin: 0, color: '#1890ff' }}>
            {collapsed ? 'DA' : 'Dev Assistant'}
          </Title>
        </div>

        {/* 自定义折叠按钮 - 放在顶部 */}
        <div style={{ 
          padding: '8px', 
          textAlign: 'right', 
          borderBottom: '1px solid #f0f0f0',
          cursor: 'pointer',
          transition: 'all 0.2s'
        }}
        onClick={() => setCollapsed(!collapsed)}
        onMouseEnter={(e) => {
          e.currentTarget.style.backgroundColor = '#f5f5f5'
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.backgroundColor = 'transparent'
        }}
        >
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </div>
        
        <Menu
          mode="inline"
          selectedKeys={[selectedKey]}
          items={menuItems}
          onClick={({ key }) => setSelectedKey(key)}
          style={{ borderRight: 0 }}
        />
      </Sider>

      {/* 右侧主内容区 */}
      <Layout className="main-content">
        {/* 顶部Header */}
        <Header className="header">
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <Title level={4} style={{ margin: 0 }}>
              {menuItems.find(item => item.key === selectedKey)?.label || '首页'}
            </Title>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <Input
              placeholder="搜索功能..."
              prefix={<SearchOutlined />}
              style={{ width: 300 }}
            />
            <Dropdown
              menu={{
                items: userMenuItems,
                onClick: handleUserMenuClick,
              }}
              placement="bottomRight"
              trigger={['click']}
            >
              <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <Avatar 
                  icon={<UserOutlined />} 
                  style={{ backgroundColor: isLoggedIn ? '#52c41a' : '#1890ff' }}
                />
                {!collapsed && (
                  <span style={{ color: '#666', fontSize: '14px' }}>
                    {isLoggedIn ? userInfo.name : '未登录'}
                  </span>
                )}
              </div>
            </Dropdown>
          </div>
        </Header>

        {/* 内容区域 */}
        <Content className="content-area">
          {renderContent()}
        </Content>
      </Layout>

      {/* 登录/注册弹窗 */}
      <Modal
        title={
          <div style={{ textAlign: 'center', fontSize: '18px', fontWeight: 'bold' }}>
            {modalType === 'login' ? '用户登录' : '用户注册'}
          </div>
        }
        open={isModalVisible}
        onCancel={handleModalCancel}
        footer={null}
        width={400}
        centered
        destroyOnHidden
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFormSubmit}
          autoComplete="off"
        >
          {modalType === 'register' && (
            <Form.Item
              name="username"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 2, max: 20, message: '用户名长度为2-20个字符' }
              ]}
            >
              <Input placeholder="请输入用户名" size="large" />
            </Form.Item>
          )}

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" size="large" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入密码" size="large" />
          </Form.Item>

          {modalType === 'register' && (
            <Form.Item
              name="confirmPassword"
              label="确认密码"
              dependencies={['password']}
              rules={[
                { required: true, message: '请确认密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'))
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" size="large" />
            </Form.Item>
          )}

          <Form.Item style={{ marginBottom: 0 }}>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              style={{ width: '100%', height: '40px' }}
            >
              {modalType === 'login' ? '登录' : '注册'}
            </Button>
          </Form.Item>

          <div style={{ textAlign: 'center', marginTop: '16px' }}>
            <span style={{ color: '#666' }}>
              {modalType === 'login' ? '还没有账号？' : '已有账号？'}
            </span>
            <Button
              type="link"
              onClick={switchModalType}
              style={{ padding: 0, marginLeft: '4px' }}
            >
              {modalType === 'login' ? '立即注册' : '立即登录'}
            </Button>
          </div>
        </Form>
      </Modal>
    </Layout>
  )
}

// 首页内容
function HomeContent() {
  return (
    <div>
      <Title level={2}>欢迎使用 Dev Assistant</Title>
      <Text type="secondary">您的专属生产力工具</Text>
      
      <Divider />
      
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '16px', marginTop: '24px' }}>
        <Card title="写作助手" hoverable>
          <p>AI驱动的写作工具，帮助您快速生成高质量内容</p>
        </Card>
        <Card title="代码生成" hoverable>
          <p>智能代码生成和优化，提升开发效率</p>
        </Card>
        <Card title="AI 对话" hoverable>
          <p>与AI助手对话，获取专业建议和解答</p>
        </Card>
        <Card title="实用工具" hoverable>
          <p>各种实用工具，满足日常开发需求</p>
        </Card>
      </div>
    </div>
  )
}

import WritingAssistant from './components/WritingAssistant'
import Calculator from './components/Calculator'
import AIChat from './components/AIChat'
import CodeGenerator from './components/CodeGenerator'
import FormatConverter from './components/FormatConverter'

// 写作助手内容
function WritingContent() {
  return <WritingAssistant />
}

// 代码生成内容
function CodeContent() {
  return <CodeGenerator />
}

// AI对话内容
function ChatContent() {
  return <AIChat />
}

// 计算器内容
function CalculatorContent() {
  return <Calculator />
}

// 格式转换内容
function ConverterContent() {
  return <FormatConverter />
}

// 文档中心内容
function DocsContent() {
  return (
    <div>
      <Title level={2}>文档中心</Title>
      <Text type="secondary">技术文档和帮助中心</Text>
      
      <Divider />
      
      <Card>
        <p>文档中心功能正在开发中...</p>
      </Card>
    </div>
  )
}

// 设置内容
function SettingsContent() {
  return (
    <div>
      <Title level={2}>设置</Title>
      <Text type="secondary">应用配置和个性化设置</Text>
      
      <Divider />
      
      <Card>
        <p>设置功能正在开发中...</p>
      </Card>
    </div>
  )
}
